﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using rpxlogindemo.extensionMethods;
using rpxnow_library.membership;

namespace rpxlogindemo.pages
{
    public partial class User : BasePage
    {
        private string userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.LoadUser();
        }

        public override void DataBind()
        {
            var user = Membership.GetUser(this.userName) as OpenIdMembershipUser;
            if (user != null)
            {
                this.litUserName.Text = user.UserName;
                this.imgPhoto.ImageUrl = user.photo;
                this.imgPhoto.AlternateText = user.realName;

                var info = new Dictionary<String, String>();
                info.Add("Name", user.realName);
                info.Add("Member since", user.CreationDate.ToPretty());
                info.Add("Website", user.url.ToHyperlink());

                this.lvAboutMe.DataSource = info.Where(i => !string.IsNullOrEmpty(i.Value));

                this.BindPageTitle(user);
            }
            else
            {
                this.RedirectToUsersPage();
            }

            base.DataBind();
        }

        private void BindPageTitle(OpenIdMembershipUser user)
        {
            if (user.UserName != user.realName)
                Page.Title = String.Format("{0} ({1})", user.UserName, user.realName);
            else
                Page.Title = user.UserName;
        }

        private void LoadUser()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["u"]))
                this.userName = Request.QueryString["u"];
            else if (Page.User.Identity.IsAuthenticated)
                this.userName = Page.User.Identity.Name;
            else
                this.RedirectToUsersPage();
        }

        private void RedirectToUsersPage()
        {
            Response.Redirect("Default.aspx");
        }
    }
}